package org.example.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.LoginRequestPacket;
import org.example.LoginResponsePacket;
import org.example.im.SessionUtil;

import java.util.Date;

public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket loginRequestPacket) {
        System.out.println(new Date() + ":================NEW SESSION  收到客户端登录请求……");

        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(loginRequestPacket.getVersion());
        System.out.println("登录信息：" + loginRequestPacket);
        if (valid(loginRequestPacket)) {
            loginResponsePacket.setSuccess(true);
            System.out.println(new Date() + ":" +
                    loginRequestPacket.getUsername() + ": 登录成功! 记录用户id、连接channel的绑定映射信息。");

            // 获取一个随机用户id
            String userId = SessionUtil.randomUserId();
            System.out.println("生成的用户id：" + userId);

            loginResponsePacket.setUserId(userId);
            // 绑定关系、标记登录
            SessionUtil.bindChannel(userId, ctx.channel());
            System.out.println("登陆后是否绑定完毕：" + SessionUtil.hasLogin(ctx.channel()));
        } else {
            loginResponsePacket.setReason("账号密码校验失败");
            loginResponsePacket.setSuccess(false);
            System.out.println(new Date() + ": 登录失败!");
        }

        // 登录响应
        ctx.channel().writeAndFlush(loginResponsePacket);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 断线取消绑定
        SessionUtil.unBind(ctx.channel());
    }

    private boolean valid(LoginRequestPacket loginRequestPacket) {
        return true;
    }
}
